import SparkMD5 from "spark-md5";
import request from "@/utils/request"
// 获取上传参数
export async function getFormData(md5) {
  if (!md5 || !/[0-9a-f]{32}/gi.test(md5)) {
    alert("md5 未计算正确");
    return undefined;
  }
  let url = "https://api.job.sunxinao.cn/files-action/oss/param/" + md5;
  try {
    let code = (await request.get(url))["data"];
    return eval(code);
  } catch (e) {
    console.error(e);
    return undefined;
  }
}

/**
 * 计算文件 md5
 * @param file 浏览器文件 (File|Blob) 对象
 * @param onProgress 进度回调
 * @returns {Promise<string>} 异步返回 md5
 */
export function md5_file(file, onProgress = undefined) {
  return new Promise(function(resolve, reject) {
    let blobSlice =
      File.prototype.slice ||
      File.prototype.mozSlice ||
      File.prototype.webkitSlice;
    let chunkSize = 2097152; // 分为 2MB 的块
    let chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;
    let spark = new SparkMD5.ArrayBuffer();
    let fileReader = new FileReader();

    fileReader.onload = function(e) {
      spark.append(e.target.result);
      currentChunk++;

      if (currentChunk < chunks) {
        loadNext();
      } else {
        onProgress && onProgress(file.size, file.size);
        resolve(spark.end());
      }
    };

    fileReader.onerror = function(e) {
      reject(e);
    };

    function loadNext() {
      const start = currentChunk * chunkSize;
      let end;
      if (start + chunkSize >= file.size) {
        end = file.size;
      } else {
        end = start + chunkSize;
      }
      onProgress && onProgress(start, file.size);
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }

    loadNext();
  });
}
